﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace Chat
{
    /// <summary>
    /// Factory for creating instanses inherited from abstract
    /// Connection and CmdSerializer classes.
    /// </summary>
    /// <typeparam name="OutCmd"></typeparam>
    public class ConnectionFactory<OutCmd> where OutCmd : Command
    {
        /// <summary>
        /// Method to use at client side. Creates a pair of Connection and CmdSerializer
        /// for the specified IP endpoint (ip + port)
        /// </summary>
        /// <param name="ipEndPoint">The IP endpoint to cretae the Connection and CmdSerializer for.</param>
        /// <returns>A pair of Connection and CmdSerializer for the specified IP endpoint.</returns>
        public static KeyValuePair<Connection<OutCmd>, CmdSerializer<OutCmd>> Create(
            IPEndPoint ipEndPoint)
        {
            return new KeyValuePair<Connection<OutCmd>, CmdSerializer<OutCmd>>(
                new TcpConnection<OutCmd>(ipEndPoint),
                new CmdBinSerializer<OutCmd>());
        }

        /// <summary>
        /// Method to use at server side. Creates CmdSerializer instanse 
        /// appropriate for the specified Connection.
        /// </summary>
        /// <param name="connection">Connection to create an appropriate serializer for.</param>
        /// <returns>CmdSerializer based class, appropriate for the specified Connection instanse.</returns>
        public static CmdSerializer<OutCmd> CreateSerializer(Connection<OutCmd> connection)
        {
            if (connection is TcpConnection<OutCmd>)
                return new CmdBinSerializer<OutCmd>();
            else
                throw new ApplicationException(
                    string.Format("Unsupported connection type: ", connection.GetType()));
        }
    }
}
